import React, { Component } from "react";
import { Input, Button, message } from "antd";

class TransactionForm extends Component {
  constructor(props) {
    super(props);

    const { modalType, coin, exType } = props;
    const { minVolume } = coin;
    let myExMinVolume = "";

    if (exType === "buy") {
      myExMinVolume = minVolume;
    } else {
      myExMinVolume = 1;
    }

    this.state = {
      price: this.props.price || "",
      volume: this.props.volume || "",
      exMinVolume: myExMinVolume,
      amount: ""
    };
  }

  handleSubmit = e => {
    e.preventDefault();
    const { exType, coin, modalType, minExVolume, maxLimitVolume } = this.props;
    const { minPrice, maxPrice, minVolume, maxVolume } = coin;
    const { price, volume, exMinVolume } = this.state;

    if (modalType === "adverst") {
      // 发广告
      if (Number(price) > 0 && Number(volume) > 0 && Number(exMinVolume) > 0) {
        const { onSubmit } = this.props;

        if (
          Number(price) >= Number(minPrice) &&
          Number(price) <= Number(maxPrice)
        ) {
          if (
            Number(volume) >= Number(minVolume) &&
            Number(volume) <= Number(maxVolume)
          ) {
            if (Number(volume) >= Number(exMinVolume)) {
              if (exType === "buy") {
                // 买入 最小成交数量要大于 minVolume
                if (Number(exMinVolume) >= Number(minVolume)) {
                  onSubmit &&
                    onSubmit({
                      price,
                      volume,
                      exType,
                      minExVolume: exMinVolume
                    });
                } else {
                  message.destroy();
                  message.error(`最小成交数量不能小于${minVolume}`);
                }
              } else {
                onSubmit &&
                  onSubmit({ price, volume, exType, minExVolume: exMinVolume });
              }
            } else {
              message.destroy();
              message.error("挂单数量不能小于最小成交数量");
            }
          } else {
            message.destroy();
            message.error("数量不在范围之内");
          }
        } else {
          message.destroy();
          message.error("价格不在范围之内");
        }
      } else {
        message.destroy();
        message.error("请先输入数量,价格以及最小成交量");
      }
    } else {
      // 买入 和卖出
      if (Number(price) > 0 && Number(volume) > 0) {
        if (
          Number(volume) >= Number(minExVolume) &&
          Number(volume) <= Number(maxLimitVolume)
        ) {
          const { onSubmit } = this.props;

          onSubmit && onSubmit({ price, volume, exType });
        } else {
          message.destroy();
          message.error("数量不在范围之内");
        }
      } else {
        message.destroy();
        message.error("请输入数量");
      }
    }
  };

  // 计算手续费
  getTradeFee = volume => {
    const { coin, modalType, exType } = this.props;
    const { feeType, sellFee, sellFeeStep } = coin;
    const account = JSON.parse(sessionStorage.getItem("account"));
    if (
      account.tag &&
      (account.tag.indexOf("FM") || account.tag.indexOf("YS"))
    ) {
      return 0;
    }
    let tradeFee = 0;
    if (exType === "sell") {
      if (feeType === "0") {
        // 不收手续费
        tradeFee = 0;
      } else if (feeType === "1") {
        if (sellFeeStep) {
          let point = sellFeeStep.split("|")[0];
          let feeValue = sellFeeStep.split("|")[1];
          if (volume > 0) {
            let number = parseInt(volume / point);
            let yu = volume % point;
            if (yu > 0) {
              tradeFee = (number + 1) * feeValue;
            } else {
              tradeFee = number * feeValue;
            }
          }
        }
        // 按固定值收
      } else if (feeType === "2") {
        // 按比例收取
        if (sellFee) {
          tradeFee = volume * sellFee;
        }
      }
    }
    return tradeFee;
  };

  handlePrice = e => {
    const { coin } = this.props;
    const pointPrice = coin.pointPrice || 4;
    const price = e.target.value;
    const reg = new RegExp(`^\\d{0,8}(\\.\\d{0,${pointPrice}})?$`);
    if (reg.test(price)) {
      const reg = new RegExp(`(\\d{0,8})(\\.\\d{0,2})?`);
      let { volume } = this.state;

      let amount = (price * 10000 * (volume > 0 ? volume : 0)) / 10000;
      amount = String(amount).match(reg)[0];
      this.setState({ price, amount });
    }
  };

  handleVolume = e => {
    const { coin } = this.props;

    let pointVolume = coin.pointVolume;
    let reg = new RegExp(`^\\d{0,8}(\\.\\d{0,${pointVolume}})?$`);
    if (pointVolume === 0) {
      pointVolume = 0;
      reg = new RegExp(`^\\d{0,8}(\\d{0,${pointVolume}})?$`);
    } else {
      pointVolume = pointVolume || 4;
      reg = new RegExp(`^\\d{0,8}(\\.\\d{0,${pointVolume}})?$`);
    }
    let volume = e.target.value;
    if (reg.test(volume)) {
      const reg = new RegExp(`(\\d{0,8})(\\.\\d{0,2})?`);
      const { price } = this.state;
      let amount = (price * 10000 * (volume > 0 ? volume : 0)) / 10000;
      amount = String(amount).match(reg)[0];
      this.setState({ volume, amount });
    }
  };

  handleExMinVolume = e => {
    const { coin } = this.props;

    let pointVolume = coin.pointVolume;
    let reg = new RegExp(`^\\d{0,8}(\\.\\d{0,${pointVolume}})?$`);
    if (pointVolume === 0) {
      pointVolume = 0;
      reg = new RegExp(`^\\d{0,8}(\\d{0,${pointVolume}})?$`);
    } else {
      pointVolume = pointVolume || 4;
      reg = new RegExp(`^\\d{0,8}(\\.\\d{0,${pointVolume}})?$`);
    }
    let volume = e.target.value;
    if (reg.test(volume)) {
      this.setState({ exMinVolume: volume });
    }
  };

  handleAmount = e => {
    const amount = e.target.value;
    const { coin } = this.props;
    let pointVolume = coin.pointVolume;
    let reg = new RegExp(`(\\d{0,8})(\\.\\d{0,${pointVolume}})?`);
    if (pointVolume === 0) {
      pointVolume = 0;
      reg = new RegExp(`(\\d{0,8})(\\d{0,${pointVolume}})?`);
    } else {
      pointVolume = pointVolume || 4;
      reg = new RegExp(`(\\d{0,8})(\\.\\d{0,${pointVolume}})?`);
    }
    if (/^\d{0,8}\.{0,1}\d{0,2}$/.test(amount)) {
      let volume = amount / this.state.price;
      volume = String(volume).match(reg)[0];
      this.setState({ amount });
      if (this.state.price > 0) {
        this.setState({ volume });
      }
    }
  };

  render() {
    const {
      localization,
      coin,
      exType,
      freezePrice,
      modalType,
      minExVolume,
      maxLimitVolume,
      myProperty
    } = this.props;
    const { price, volume, amount, exMinVolume } = this.state;
    const typeText = {
      buy: localization["买入"],
      sell: localization["卖出"]
    };

    const { feeType } = coin;

    let pointVolume = coin.pointVolume;
    let reg = new RegExp(`(\\d{0,8})(\\.\\d{0,${pointVolume}})?`);
    if (pointVolume === 0) {
      pointVolume = 0;
      reg = new RegExp(`(\\d{0,8})(\\d{0,${pointVolume}})?`);
    } else {
      pointVolume = pointVolume || 4;
      reg = new RegExp(`(\\d{0,8})(\\.\\d{0,${pointVolume}})?`);
    }

    let tradeFee = this.getTradeFee(volume);
    const limitText = exType === "buy" ? "买入" : "卖出";
    return (
      <ul className="c2c-form">
        <li>
          <Input
            addonBefore={`${localization["价格"]}（CNY）`}
            size="large"
            value={price}
            placeholder={localization["请输入价格"]}
            disabled={freezePrice}
            onChange={this.handlePrice}
          />
          {modalType === "adverst" && (
            <p className="price-limit">
              委托价格范围
              <span> {coin.minPrice} </span> 到 <span> {coin.maxPrice} </span>
            </p>
          )}
        </li>
        <li>
          <Input
            addonBefore={`${localization["数量"]}（${coin.symbol}）`}
            size="large"
            value={volume}
            placeholder={
              modalType === "trade" && exType === "sell"
                ? `请输入数量 (可卖: ${myProperty})`
                : "请输入数量"
            }
            onChange={this.handleVolume}
          />
          {modalType === "adverst" && (
            <p className="volume-limit">
              委托数量范围
              <span> {coin.minVolume} </span> 到 <span> {coin.maxVolume}</span>
              {exType === "sell" && (
                <span className="property">
                  可卖出数量
                  <span style={{ color: "#d4a668" }}> {myProperty}</span>
                </span>
              )}
            </p>
          )}
          {modalType === "trade" && (
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                marginTop: 6
              }}
            >
              <div>
                {limitText}最小限额：
                <span
                  style={{ color: "#d4a668", marginLeft: 6 }}
                  className="property"
                >
                  {minExVolume}
                </span>
              </div>
              <div>
                单据剩余数量：
                <span
                  style={{ color: "#d4a668", marginLeft: 6 }}
                  className="property"
                >
                  {maxLimitVolume}
                </span>
              </div>
            </div>
          )}
        </li>
        {modalType === "adverst" && (
          <li style={{ marginBottom: 20 }}>
            <Input
              addonBefore={`最小成交数量`}
              size="large"
              value={exMinVolume}
              placeholder={"请输入最小成交数量"}
              onChange={this.handleExMinVolume}
            />
          </li>
        )}

        <li>
          <Input
            addonBefore={`${localization["总额"]}（CNY）`}
            size="large"
            value={amount}
            placeholder={localization["请输入总额"]}
            onChange={this.handleAmount}
          />
        </li>
        {exType === "buy" && (
          <p className="c2c-buy-text">
            买卖交易必须30分钟内完成支付,否则系统自动取消交易。
          </p>
        )}
        {exType === "sell" && modalType === "adverst" && feeType !== "0" && (
          <p style={{ color: "#dadada" }}>
            手续费
            <span style={{ color: "#d4a668" }}>
              {" "}
              {String(tradeFee).match(reg)[0]}{" "}
            </span>
            , 挂单成功扣除手续费，撤销广告手续费不返还
          </p>
        )}

        <li className="c2c-submit-btn">
          <Button type={exType} size="large" onClick={this.handleSubmit}>
            <i className="iconfont icon-jia" />
            {`${typeText[exType]} ${coin.symbol}`}
          </Button>
        </li>
      </ul>
    );
  }
}

export default TransactionForm;
